package com.study.hot.jetpack.livedata

import android.util.Log
import androidx.annotation.MainThread
import androidx.lifecycle.LiveData
import java.math.BigDecimal

/**
 * <pre>
 *     author : slx
 *     time   : 2021/02/24
 *     desc   : 通常用户只关心界面活跃/非活跃状体，可以扩展LiveData，自定义LiveData实现单例，可以在不同Activity/Fragment中传值
 * </pre>
 */
class StockLiveData(symbol: String) : LiveData<BigDecimal>() {
    private val stockManager = StockManager(symbol)
    private val listener = { price: BigDecimal ->
        Log.i("fauks", "price:${price.toInt()}")
        value = price
    }

    // 活跃状态
    override fun onActive() {
        super.onActive()
        stockManager.requestPriceUpdates(listener)
    }

    override fun onInactive() {
        super.onInactive()
        stockManager.removeUpdates(listener)
    }

    companion object {
        private lateinit var sInstance: StockLiveData

        @MainThread
        fun get(symbol: String): StockLiveData {
            sInstance = if (::sInstance.isInitialized) sInstance else StockLiveData(symbol)
            return sInstance
        }
    }
}

class StockManager(val symbol: String) {
    fun requestPriceUpdates(listener: (price: BigDecimal) -> Unit) {
        Log.i("fauks", "StockManager:$symbol up")
        for (i in 0..10) {
            listener.invoke(BigDecimal(i))
        }
    }

    fun removeUpdates(listener: (price: BigDecimal) -> Unit) {
        Log.i("fauks", "StockManager:$symbol down")
        for (i in 10 downTo 0) {
            listener.invoke(BigDecimal((i)))
        }
    }
}